package com.easygem.controller.front;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.easygem.common.model.front.CallLog;
import com.easygem.common.model.front.ResourceInfo;
import com.easygem.common.model.system.User;
import com.easygem.common.response.ActiveUser;
import com.easygem.common.response.ResponseBean;
import com.easygem.front.service.CallService;
import com.easygem.front.service.ResourceInfoService;
import com.easygem.front.service.SeatService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 廖思炜
 * @version 1.0
 * @className CallController
 * @Description TODO 通话统计
 * @date 2025/3/25 9:14
 */
@RestController
@RequestMapping("/comcentre/call")
public class CallController {
    @Autowired
    private CallService callService;
    @Autowired
    private SeatService seatService;
    @Autowired
    private ResourceInfoService resourceInfoService;

    @ApiOperation("得到当前用户绑定手机号")
    @GetMapping("/getCallerNbr")
    public ResponseBean getCallerNbr() {
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        return ResponseBean.success(user.getPhone());
    }

    @ApiOperation("得到当前用户所属账号的中间号")
    @GetMapping("/getBindNbr")
    public ResponseBean getBindNbr() {
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        String bindNbr=callService.getBindNbrById(user.getUserId());
        return ResponseBean.success(bindNbr);
    }

    @ApiOperation("得到签名")
    @PostMapping("/getSign")
    public ResponseBean getSign(@RequestBody Map<String, Object> params){
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        if (params.containsKey("callerNbr")&&params.containsKey("calleeNbr")&&params.containsKey("bindNbr")){
            int isBlack =resourceInfoService.isBlacklist(params.get("calleeNbr").toString());
            if (isBlack > 0) {
                return ResponseBean.error("不可拨打黑名单");
            }
            if (callService.checkResource(params.get("calleeNbr").toString())<=0&&callService.checkResourceB(params.get("calleeNbr").toString())<=0){
                return ResponseBean.error("该号码无法外呼！资源/客户不存在");
            }
            if (user.getType()!=2){
                return ResponseBean.error("非员工，无法外呼拨打号码");
            }
            Integer status=seatService.checkStatus(user);
            if (status>0){
                String sign = sign(params, callService.getAppSecretByName(user.getAccountName()));
                return ResponseBean.success(sign);
            }else {
                return ResponseBean.error("未开启外呼");
            }
        }else {
            String sign = sign(params, callService.getAppSecretByName(user.getAccountName()));
            return ResponseBean.success(sign);
        }

    }
    @ApiOperation("得到签名简易过滤版")
    @PostMapping("/getSignOp")
    public ResponseBean getSignOp(@RequestBody Map<String, Object> params){
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        if (user.getType()!=2){
            return ResponseBean.error("非员工，无法外呼拨打号码");
        }
        Integer status=seatService.checkStatus(user);
        if (status>0){
            String sign = sign(params, callService.getAppSecretByName(user.getAccountName()));
            return ResponseBean.success(sign);
        }else {
            return ResponseBean.error("未开启外呼");
        }
    }
    @ApiOperation("得到appId")
    @GetMapping("/getAppId")
    public ResponseBean getAppId() {
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        return ResponseBean.success(callService.getAppIdByName(user.getAccountName()));
    }

    @ApiOperation("得到sessionId")
    @GetMapping("/getSessionId")
    public ResponseBean getSessionId() {
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        return ResponseBean.success(callService.getSessionId(user.getAccountName()));
    }
    @ApiOperation("话单基本信息保存")
    @PostMapping("/saveLog")
    public ResponseBean saveLog(@RequestBody CallLog callLog) {

        if (callLog.getSessionId()==null){
            return ResponseBean.error("非法参数");
        }
        ActiveUser activeUser=(ActiveUser) SecurityUtils.getSubject().getPrincipal();
        User user = activeUser.getUser();
        //设置当前话单为当前登录的用户所拨打

        callLog.setUserId(user.getUserId());
        ResourceInfo getName=callService.selectResourceNameByPhoneA(callLog.getCalleeNbr());
        //检查被叫的号码所属的资源名称
        if (getName==null||getName.getResourceName()==null){
            getName=callService.selectResourceNameByPhoneB(callLog.getCalleeNbr());
            if (getName==null||getName.getResourceName()==null){
                callLog.setResourceName(null);
            }else {
                callLog.setResourceName(getName.getResourceName());
            }
        }else {
            callLog.setResourceName(getName.getResourceName());
        }
        callLog.setAccountName(user.getAccountName());
        callLog.setCircuitTariff(callService.getTariffByUserId(user.getUserId()));
        callLog.setEndTime(new Date());
        if (callLog.getCircuitTariff()==null){
            callLog.setCircuitTariff(0.0);
        }
        if (callService.saveLog(callLog)>0){
            callService.updatedAccountCallNum();//使当前账号通话数+1,并且更新最后拨打时间
            Map<String,Object> map2=new HashMap<>();
            map2.put("resourceId",getName.getResourceId());
            map2.put("isCall",1);
            map2.put("lastCallTime", Timestamp.valueOf(LocalDateTime.now()));
            map2.put("editTime", Timestamp.valueOf(LocalDateTime.now()));
            callService.updatedResourceCallInfo(map2);//更新资源，并更新是否拨打呼叫状态，最后呼叫时间
            return ResponseBean.success("通话记录已保存，正等待通话完成后记录详细数据");
        }else {
            return ResponseBean.error("服务器内部错误,无法保存");
        }
    }

    @ApiOperation("话单推送回调接口")
    @PostMapping("/callBackSaveLog")
    public ResponseBean callBackSaveLog(@RequestBody Map<String,Object> map) {
        System.out.println(":::::::::::"+map.toString());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        //对象转换
        // 转换为 java.util.Date
        Date startTime =new Date((Long)map.get("startTime"));
        Date endTime = new Date((Long)map.get("endTime"));

        CallLog callLog=new CallLog();
        callLog.setStartTime(startTime);
        callLog.setEndTime(endTime);
        callLog.setSessionId((String)map.get("sessionId"));
        callLog.setBindNbr((String)map.get("bindNbr"));
        callLog.setCallerNbr((String)map.get("callerNbr"));
        callLog.setCalleeNbr((String)map.get("calleeNbr"));

        if (map.get("callOutStartTime")==null){
            callLog.setCallOutStartTime(null);
        }else {
            Date callOutStartTime =new Date((Long)map.get("callOutStartTime"));
            callLog.setCallOutStartTime(callOutStartTime);
        }

        if (map.get("duration")==null){
            callLog.setDuration(null);
        }else {
            callLog.setDuration(Integer.parseInt(String.valueOf(map.get("duration"))));
        }

        if (map.get("secondsDuration")==null){
            callLog.setSecondsDuration(null);
        }else {
            callLog.setSecondsDuration(Integer.parseInt(String.valueOf(map.get("secondsDuration"))));
        }

        if (map.get("recordUrl")==null){
            callLog.setRecordUrl(null);
        }else {
            callLog.setRecordUrl((String)map.get("recordUrl"));
        }
        if (map.get("status")==null){
            callLog.setStatus(null);
        }else {
            callLog.setStatus(String.valueOf(map.get("status")));
        }

        if (map.get("ulFailReason")==null){
            callLog.setUlFailReason(null);
        }else {
            callLog.setUlFailReason(Integer.parseInt((String)map.get("ulFailReason")));
        }

        Integer check=callService.checkSessionId(callLog.getSessionId());
        if (check>0){
            //得到资费并设置消费金额
            //判断是否为null，如果为null则设置默认值0方便计算

            if (callLog.getDuration()==null){
                callLog.setDuration(0);
            }

            Double consumptionAmount=callService.getTariffBySessionId(callLog.getSessionId())*callLog.getDuration();
            callLog.setConsumptionAmount(consumptionAmount);
            callService.callBackSaveLog(callLog);
            return ResponseBean.success("保存成功");
        }else {
            return ResponseBean.error("信息无法匹配");
        }
    }

    public String sign(Map<String, Object> map, String appSecret) {
        StringBuilder sb = new StringBuilder(appSecret);
        for (Map.Entry entry : MapUtil.sort(map).entrySet()) {
            if (ObjectUtil.isNotEmpty(entry.getValue())) {
                sb.append(entry.getKey()).append(entry.getValue());
            }
        }
        return SecureUtil.md5(sb.toString()).toUpperCase();
    }

}
